import logging
import os

import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template

from datetime import datetime
from BeautifulSoup import BeautifulSoup

# template
robo_template = os.path.join(os.path.dirname(__file__), 'robo.tpl.html')

class Game:
  def __init__(self, title, ship):
    self.title = title
    self.ship = ship
    self.turns = []
    
class Turn:
  def __init__(self, datetime):
    self.datetime = datetime
    self.date = datetime.strftime('%d.%m.%Y %H:%M:%S')
    self.robots = []
    self.phases = []

  def initPhases(self):
    countPhases = max([len(robot.phases) for robot in self.robots])
    for i in range(countPhases):
      phase = []
      self.phases.append(phase)
      for robot in self.robots:
        phase.append(robot.phases[i])

class Robot:
  def __init__(self, name):
    self.name = name
    self.phases = []

class PhaseItem:
  def __init__(self, color, text):
    self.color = color
    self.text = text


class RoboHandler(webapp.RequestHandler):
  def get(self):
    # result = urlfetch.fetch('http://www.eyeplaygames.com/roborunner/games/269563/report.html')
    result = urlfetch.fetch('http://wxplclav02/wde/css/img/robo.html')

    if result.status_code == 200:
      self.response.headers['Content-Type'] = 'text/html; charset=utf-8'

      doc = BeautifulSoup(result.content, convertEntities=BeautifulSoup.ALL_ENTITIES)
      body = doc.body

      center = doc.find('center')
      fonts = center.findAll('font')

      game = Game(fonts[0].string.strip(), fonts[1].string.strip())

      table = doc.find('table')

      while table:
        date = table.find('font')

        if date:
          table = table.findNextSibling('table')
          if table:
            turn = Turn(datetime.strptime(date.string.strip(), '%a %b %d %H:%M:%S %Y')) #%Z
            game.turns.append(turn)

            rows = table.findAll('tr')
            
            for row in rows:
              col = row.find('td')
              if col:
                robot = Robot(col.font.b.string.strip())
                turn.robots.append(robot)

                for td in col.findNextSiblings('td'):
                  phase = []
                  robot.phases.append(phase)

                  for font in td.findAll('font'):
                    color = font['color']
                    text = ''.join(font.findAll(text=True)).strip()
                    phase.append(PhaseItem(color, text))

            turn.initPhases()

            table = table.findNextSibling('table')

      template_values = { 'game': game }

      self.response.out.write(template.render(robo_template, template_values))

    else:
      self.response.headers['Content-Type'] = 'text/plain'
      self.response.out.write('nothing in ' + str(result.status_code))
  
def main():
  application = webapp.WSGIApplication(
    [('/robo', RoboHandler)],
    debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
